import React, {Component} from 'react';

import {Button, notification, Icon} from 'antd';

import {STAY, TRAIL} from "../../config/const";
import {FETCH_DEVICES} from "../../models/device/const";
import {TEMPLATE_POINT} from "../../models/myDevice/const";
import moment from 'moment'
// import getDeviceList from "../../models/selectors";
import {connect} from "react-redux";
import BasicMap from "./BasicMap";
import {fetchLatestStaysList, fetchStaysList, fetchTrailList} from "../../services/map";
import {getCurrent, getDemoId, getLine} from "../../services/new";
import DeviceList from "../MyMap/DeviceList";
import {base_url,base_url1} from '../../config/const'

//json
import stayLists from './userstays'

import StayList from './StayList'
import {secs2time, ts2time} from "../../utils/utils";
import request from '@/utils/request';
import {wgs84tobd09} from "../../utils/coordtransform";

/**
 * 需要有返回值：且和 dispatch({
            type: TEMPLATE_POINT,
        });
 */
// @connect((device) => {
    // var currentPoint=device.new.Current_aList;
    // // 这里返回的给了this.props
    // return ({currentPoint})
// })

function fullscreenchange(el, callback) {
    el.addEventListener("fullscreenchange", function () {
        callback && callback(document.fullscreen);
    });
    el.addEventListener("webkitfullscreenchange", function () {
        callback && callback(document.webkitIsFullScreen);
    });
    el.addEventListener("mozfullscreenchange", function () {
        callback && callback(document.mozFullScreen);
    });
    el.addEventListener("msfullscreenchange", function () {
        callback && callback(document.msFullscreenElement);
    });
}
class Index extends Component {
    constructor(props) {
        super(props);
        this.state = {
            checkedKeys: [],//选中的多个设备
            demoId: [],
            searchDemoId: [],
            infoWindowPosition: null,
            infoWindowText: '',
            cur_device: [],
            stayLists: [],//停留点数据,每个数组是一个对象包含天
            trailList: [],
            datePickerVisible: false,//选择停留轨迹后选择日期
            type: STAY,
            start_time: undefined,
            end_time: undefined,
            deviceListVisible: false,
            stayListVisible: false,
            selectDate: null,
            center: {lng: 108.93, lat: 34.27},
            isTrail: false,
            deviceListFilter: '',
            nextStatus: true,//用的disable所以是false
            prevStatus: false,
            today: moment(),
            lineData: {
                day: '',
                data: [],
                device_id: ''
            },
            lines: [],
            currentPoint: [],
            isFullScreen:false,
            mileage:{},

            activeTableIdx:0,//针对下面停留点表格索引，比较开始时间
            playIdx:0,//这是线上点
            playPosition:{device_name:'',time:''},
            isPlay:false,
            playSpeed:'10000',//值越小越慢
            progress:0
        };
        // const {dispatch} = this.props;//注意这里需要dispatch一下
        // dispatch({
        //     type: TEMPLATE_POINT,
        // });
    }
    componentDidMount() {
        var that=this;
        // this.getCurrentPointHandler();
        this.getCurrentPoint();
        this.getDemoId();
        this.getMileage();
        // this.getStayPoints()
        fullscreenchange(document, function(isFull) {
            that.setState({isFullScreen: isFull})
        });
        document.onkeydown = (event) => { //监听整个键盘的onkeydown事件
            if ( event.keyCode == 122) {
                event.preventDefault(); //阻止浏览器的默认行为
                this.handleRequestFullScreen(); //调用H5的api
            }
        };
    }
    handleRequestFullScreen = () => {
        const {isFullScreen} = this.state;
        const element = document.documentElement;
        if (isFullScreen) {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            }
            this.setState({isFullScreen: false})
        } else {
            if (element.requestFullscreen) {
                element.requestFullscreen();
            } else if (element.mozRequestFullScreen) {
                element.mozRequestFullScreen();
            } else if (element.webkitRequestFullscreen) {
                element.webkitRequestFullscreen();
            } else if (element.msRequestFullscreen) {
                element.msRequestFullscreen();
            }
            this.setState({isFullScreen: true})
        }
    };
    openNotification = (today, device_id) => {
        device_id=this.idToName(device_id);
        notification.open({
            message: '提示',
            description:
                ` ${device_id}在  ${today}  没有数据`,
            icon: <Icon type="bulb" style={{color: '#108ee9'}}/>,
        });
    };
    idToName=(id)=>{
          this.state.demoId.forEach(function (item) {
              if(item.device_id==id){
                  if(item.device_name){
                      id=item.device_name;
                  }
              }
          });
        return id;
    };
    stayHandler = (stayList, checkedKeys) => {
        const marks = [], points = [];
        stayList.forEach((item, idx) => {
            if (!item) return;
            // if (!checkedKeys.includes('' + item.deviceid)) return;
            const {startTime, endTime, lat, lng, name, address, device_id} = item;
            const xy = {
                lng: lng,
                lat: lat
            };
            const point = {
                key: idx,
                xy: [xy.lng, xy.lat],
                device_id,
                startTime,
                endTime,
                address,
                name
            };
            const mark = {xy, key: idx};
            marks.push(mark);
            points.push(point);
        });

        return {marks, points}
    };
    /**
     * 数据请求 getCurrentPoint获取当前点
     * getDemoid获取左侧列表数据
     * getStayPoints获取停留点
     * getCurrentLine获取单条线路
     * getCurrentLines获取多条线路
     */
    getCurrentPoint = async (device) => {
        if (localStorage.getItem('user')) {
            var user = JSON.parse(localStorage.getItem('user')).username;
            var company_id = JSON.parse(localStorage.getItem('user')).company_id;
        }
        var url=`template_point/?user=${user}&company_id=${company_id}`;
        const response = await new Promise(resolve => {
            request({url}).then(res => {
                resolve(res.data)
            });
        });
        this.setState({
            currentPoint: response
        })
    };
    getDemoId = async () => {
        if (localStorage.getItem('user')) {
            var user = JSON.parse(localStorage.getItem('user')).username;
            var company_id = JSON.parse(localStorage.getItem('user')).company_id;
        }
        var url=`demo_id/?user=${user}&company_id=${company_id}`;
        const response = await new Promise(resolve => {
            request({url}).then(res => {
                resolve(res.data)
            });
        });
        this.setState({
            demoId: response.device_list,
            searchDemoId: response.device_list
        })
    };
    getMileage=async ()=>{
        if (localStorage.getItem('user')) {
            var company_id = JSON.parse(localStorage.getItem('user')).company_id;
        }
        //昨天的到今天的
        var start_time=parseInt((new Date().valueOf()-24*60*60*1000)/1000);
        var end_time=parseInt((new Date().valueOf())/1000);
        var url=`device_mileage/?company_id=${company_id}&start_time=${start_time}&end_time=${end_time}`;
        const response = await new Promise(resolve => {
            request({url}).then(res => {
                resolve(res.data)
            });
        });
        var obj={};
        response.forEach(function (item) {
            obj[item.device_id]=parseInt(item.mileage||0);
        });
        this.setState({
            mileage:obj
        })
    };
    getStayPoints = async (checkedKeys) => {//获取停留点
        var that=this;
        if (localStorage.getItem('user')) {
            var user = JSON.parse(localStorage.getItem('user')).username;
            var company_id = JSON.parse(localStorage.getItem('user')).company_id;
        }
        var today = this.state.today.format('YYYY-MM-DD');
        var arr = [];
        for (let i = 0; i < checkedKeys.length; i++) {
            var url=`stay/?device_id=${checkedKeys[i]}&day=${today}&user=${user}&company_id=${company_id}`;
            const response = await new Promise(resolve => {//开服务接口
                request({url}).then(res => {
                    // resolve(res)
                    //数据分析处理
                    var result = [];
                    res.data.data.map((item, index) => {
                        item.id=index;
                        item.device_id = that.idToName(checkedKeys[i]);
                        item.day = today;
                        item.stayTime = parseInt((parseInt(item.endTime) - parseInt(item.startTime)) / 60000);
                        item.xy = [item.lng, item.lat];
                        item.endTime = moment(new Date(item.endTime)).format('YYYY-MM-DD HH:mm:ss');
                        item.startTime = moment(new Date(item.start_time)).format('YYYY-MM-DD HH:mm:ss');
                        if(!item.station_name){
                            item.station_name='未找到'
                        }
                        var duration=item.duration;
                        var day=parseInt(duration/(24*60));
                        var hour=parseInt(duration%(24*60)/60);
                        var minute=duration-day*24*60-hour*60;
                        if(day>0){
                            day=day+'天'
                        }else{
                            day=''
                        }
                        if(hour>0){
                            hour=hour+'小时'
                        }else{
                            hour=''
                        }
                        item.duration=day+hour+minute+'分钟';
                        // 只显示停留时间大于10分钟的
                        // if (item.stayTime > 10) {
                        //     result.push(item)
                        // }
                        result.push(item)

                    });
                    resolve(result);
                });
            });
            arr.push(response);
        }
        this.setState({
            stayLists: arr
        });
        return arr
    };
    getCurrentLine = async (device) => {
        if (localStorage.getItem('user')) {
            var user = JSON.parse(localStorage.getItem('user')).username;
            var company_id = JSON.parse(localStorage.getItem('user')).company_id;
        }
        var t1 = this.state.today.format('YYYY-MM-DD');
        var t2 = moment().format('YYYY-MM-DD');
        if (moment(t1).isAfter(t2) || t1 == t2) {
            this.setState({
                nextStatus: true
            })
        } else {
            this.setState({
                nextStatus: false
            })
        }
        if (this.state.today < moment("2019-09-03")) {
            this.setState({
                prevStatus: true
            })
        } else {
            this.setState({
                prevStatus: false
            })
        }
        var today = this.state.today.format('YYYY-MM-DD');
        var device_id = device || this.state.cur_device[0];
        var url=`device_line/?device_id=${device_id}&day=${today}&user=${user}&company_id=${company_id}`;
        if (device_id) {
            const response = await new Promise(resolve => {
                request({url}).then(res => {
                    var fd = [];
                    if (res.data.data) {
                        res.data.data.forEach(function (item) {
                            if (item.outlier === 0) {
                                item.device_id=device_id;
                                fd.push(item);
                            }
                        });
                        res.data.data = fd;
                    }
                    resolve(res.data)
                });
            });
            if (response.data.length > 0) {
                var center = {
                    lng: response.data[0].lat_lng[1],
                    lat: response.data[0].lat_lng[0]
                }
            } else {
                center = {lng: 108.93, lat: 34.27, name: 'xa'}
            }
            if (response.data.length === 0) {
                var that = this;
                this.getStayPoints(this.state.checkedKeys).then(res => {
                    if (res[0].length > 0) {
                        // center=res[0][0];
                        // this.setState({
                        //     center
                        // })
                    } else {
                        that.openNotification(today, device_id);
                    }
                })
            }
            this.setState({
                lineData: response,
                center,
                activeTableIdx:0,//针对下面停留点表格索引，比较开始时间
                playIdx:0,//这是线上点
                playPosition:{device_name:'',time:''},
                isPlay:false,
                progress:0
            })
        }
    };
    getCurrentLines = async (checkedKeys) => {
        if (localStorage.getItem('user')) {
            var user = JSON.parse(localStorage.getItem('user')).username;
            var company_id = JSON.parse(localStorage.getItem('user')).company_id;
        }
        var that = this;
        var t1 = this.state.today.format('YYYY-MM-DD');
        var t2 = moment().format('YYYY-MM-DD');
        if (moment(t1).isAfter(t2) || t1 == t2) {
            this.setState({
                nextStatus: true
            })
        } else {
            this.setState({
                nextStatus: false
            })
        }
        if (this.state.today < moment("2019-09-03")) {
            this.setState({
                prevStatus: true
            })
        } else {
            this.setState({
                prevStatus: false
            })
        }
        var today = this.state.today.format('YYYY-MM-DD');
        var arr = [];
        if (checkedKeys.length > 0) {
            for (let i = 0; i < checkedKeys.length; i++) {
                var url=`device_line/?device_id=${checkedKeys[i]}&day=${today}&user=${user}&company_id=${company_id}`;
                if (JSON.stringify(checkedKeys[i].length) > 5) {
                    const response = await new Promise(resolve => {
                        request({url}).then(res => {
                            var fd = [];
                            if (res.data.data) {
                                res.data.data.forEach(function (item) {
                                    if (item.outlier === 0) {
                                        fd.push(item);
                                    }
                                });
                                res.data.data = fd;
                            }
                            resolve(res.data)
                        });
                    });
                    if (response.data.length > 0) {
                        var center = {
                            lng: response.data[0].lat_lng[1],
                            lat: response.data[0].lat_lng[0]
                        }
                    } else {
                        center = {lng: 108.93, lat: 34.27}
                    }
                    arr.push(response);
                } else {
                    const response = await new Promise(resolve => {
                        request({url}).then(res => {
                            var fd = [];
                            if (res.data.data) {
                                res.data.data.forEach(function (item) {
                                    if (item.outlier === 0) {
                                        fd.push(item);
                                    }
                                });
                                res.data.data = fd;
                            }
                            resolve(res.data)
                        });
                    });
                    if (response.data.length > 0) {
                        center = {
                            lng: response.data[0].lat_lng[1],
                            lat: response.data[0].lat_lng[0]
                        }
                    } else {
                        center = {lng: 108.93, lat: 34.27}
                    }
                    arr.push(response);
                }
            }
            arr.forEach(function (item, index) {
                if (item.data.length === 0) {
                    that.getStayPoints(that.state.checkedKeys).then(res => {
                        if (res[index].length > 0) {
                            center = res[res.length - 1]
                        } else {
                            that.openNotification(today, item.device_id);
                        }
                    })

                }
            });
            this.setState({
                lines: arr,
                lineData:arr[0],
                center,
                activeTableIdx:0,//针对下面停留点表格索引，比较开始时间
                playIdx:0,//这是线上点
                playPosition:{device_name:'',time:''},
                isPlay:false,
                progress:0
            })
        }

    };
    setEventHandler = key => {
        if (key) {
            this.setState(key);
        } else {
            this.setState({key})
        }
    };
    getCurrentPointHandler = async () => {//点击当前设备的时候，清空并返回点页面
        this.setState({loading: true});
        const newState = {
            cur_device: [],
            isTrail: false,
            loading: false,
            checkedKeys: [],
            today: moment(),
            nextStatus: true,
            lines: [],
            infoWindowPosition: ''//隐藏弹框
        };
        this.setState(state => (newState));
    };
    /**
     * 点击面板触发事件----当前点弹框01
     */
    infoWindowHandler = (infoWindowPosition, info) => {
        if (!info.device_name || info.device_name === 'null') info.device_name = '';
        // info 是这一行的信息
        var time = info.time;
        const Time = moment(time).format('YYYY-MM-DD HH:mm:ss');
        const infoWindowText = `    
        <dl>
            <dt style="font-weight: bolder">设备名称:</dt>
            <span>${info.device_name}</span>
          <dt style="font-weight: bolder">设备序列号:</dt>
            <span>${info.demo_id}</span>
          <dt style="font-weight: bolder">时间:</dt>
            <span>${Time}</span>
          <dt style="font-weight: bolder">坐标:</dt>
            <span>${info.lng} , ${info.lat}<span/>
        </dl>
        <a class=${TRAIL}>停留和轨迹 <span style="display: none">${info.demo_id}</span></a>
        `;
        this.setState({
            infoWindowPosition,
            infoWindowText,
            checkedKeys: [info.demo_id],
            cur_device: [info.demo_id]
        })
    };
    /**
     * 停留点弹框02
     */
    infoWindow = (infoWindowPosition, info) => {
        const infoWindowText = `    
        <dl>
          <dt style="font-weight: bolder">设备:</dt>
            <span>${this.idToName(info.device_id)}</span>
          <dt style="font-weight: bolder">站名:</dt>
            <span>${info.station_name}</span>
          <dt style="font-weight: bolder">开始时间:</dt>
            <span>${info.startTime}</span>
          <dt style="font-weight: bolder">停留时间:</dt>
            <span>${info.duration}</span>
          <dt style="font-weight: bolder">坐标:</dt>
            <span>${infoWindowPosition.lng} , ${infoWindowPosition.lat}<span/>
        </dl>
        `;
        this.setState({
            infoWindowPosition,
            infoWindowText,
        })
    }
    //开始结束 临时使用
    infoWindowTest = (infoWindowPosition, info) => {
        const infoWindowText = `    
        <dl>
          <dt style="font-weight: bolder">设备名称:</dt>
            <span>${this.idToName(info.device_id)}</span>
          <dt style="font-weight: bolder">设备ID:</dt>
            <span>${info.device_id}</span>   
         <dt style="font-weight: bolder">时间:</dt>
            <span>${info.time}</span>
          <dt style="font-weight: bolder">坐标:</dt>
            <span>${infoWindowPosition.lng} , ${infoWindowPosition.lat}<span/>
        </dl>
        `;
        this.setState({
            infoWindowPosition,
            infoWindowText,
        })
    }
    /**
     * 抽屉
     */
    handleDeviceListVisible = () => {
        //抽屉逻辑待看
        this.setState(({deviceListVisible, checkedKeys}) => ({
            deviceListVisible: !deviceListVisible,
            infoWindowPosition: null,
            infoWindowText: '',
        }))
    };
    /**
     *  地图表格的关闭与显示
     */
    handleStayListVisible = () => {
        this.setState({
            stayListVisible: !this.state.stayListVisible,
            infoWindowPosition: null,
            infoWindowText: '',
        })
    };

    /**
     * 时间选择
     */
    getDate = (date, dateString) => {
        this.setState({
            today: date,
            infoWindowPosition: '',
            lineData: {
                day: '',
                data: [],
                device_id: '',
                activeTableIdx:0,//针对下面停留点表格索引，比较开始时间
                playIdx:0,//这是线上点
                playPosition:{device_name:'',time:''},
                isPlay:false,
                progress:0
            },
            lines: [],
        }, () => {
            if (this.state.checkedKeys.length >= 1) {
                this.getCurrentLines(this.state.checkedKeys);//获取日期today
            } else {
                this.getCurrentLine();//获取日期today
            }
            this.getStayPoints(this.state.checkedKeys);
        });

    };
    prevDay = () => {
        this.setState({
            today: this.state.today.add(-1, 'days'),
            infoWindowPosition: '',
            lineData: {
                day: '',
                data: [],
                device_id: ''
            },
            lines: [],
            activeTableIdx:0,//针对下面停留点表格索引，比较开始时间
            playIdx:0,//这是线上点
            playPosition:{device_name:'',time:''},
            isPlay:false,
            progress:0
        });
        this.getCurrentLines(this.state.checkedKeys);//获取日期today
        this.getStayPoints(this.state.checkedKeys);
    };
    nextDay = () => {

        this.setState({
            today: this.state.today.add(1, 'days'),
            nextStatus: true,
            lineData: {
                day: '',
                data: [],
                device_id: ''
            },
            lines: [],
            infoWindowPosition: '',//隐藏弹框
            activeTableIdx:0,//针对下面停留点表格索引，比较开始时间
            playIdx:0,//这是线上点
            playPosition:{device_name:'',time:''},
            isPlay:false,
            progress:0
        });
        this.getCurrentLines(this.state.checkedKeys);
        this.getStayPoints(this.state.checkedKeys);
    };
    onCheck = checkedKeys => {
        // console.log('点击复选框执行事件', checkedKeys);
        if (checkedKeys.length > 0) {
            this.setState({
                checkedKeys,
                cur_device: checkedKeys,
                isTrail: true,
                infoWindowPosition: '',//隐藏弹框
                lineData: {
                    day: '',
                    data: [],
                    device_id: ''
                },
            });
            this.getCurrentLines(checkedKeys);
        } else {
            this.setState({
                checkedKeys,
                cur_device: checkedKeys,
                infoWindowPosition: '',//隐藏弹框
                isTrail: false,
                nextStatus: true,//用的disable所以是false
                prevStatus: false,
                today: moment().add(-1, 'days'),
                lineData: {
                    day: '',
                    data: [],
                    device_id: ''
                },
            });
        }
        this.getStayPoints(checkedKeys);
    };
    /**
     * 点击设备ID：单击设备名称执行事件
     */
    onSelect = (selectedKeys, info) => {

        this.setState({
            cur_device: selectedKeys,
            isTrail: true,
            infoWindowPosition: '',
            checkedKeys: selectedKeys,
            lines: []
        });
        this.getCurrentLine(selectedKeys[0]);
        this.getStayPoints(selectedKeys);
    };
    onChange = e => {
        const {value} = e.target;
        let arr = [];
        this.state.demoId.map((item, index) => {
           var str=item.device_id+item.device_name;
            if (str.indexOf(value) > -1) {
                arr.push(item)
            }
        });
        this.setState({
            searchDemoId: arr
        })
    };
    /**
     * 全不选：清空key----清空线路数据
     */
    clearCheckKeys = () => {
        this.setState({
            checkedKeys: [],//选中的多个设备
            isTrail: false,
            nextStatus: true,//用的disable所以是false
            prevStatus: false,
            today: moment(),
            infoWindowPosition: '',
            lineData: {
                day: '',
                data: [],
                device_id: ''
            },
            lines: [],
        })
    };
    /**
     * 产生不同颜色:red black blue yellow
     */
    getRandomLineColor = (idx) => {
        var colors = {
            "204": 'red',
            "205": 'blue',
            "206": 'green',
            "207": '#ffba37',
            "208": 'yellow',
            "209": '#008080',
            "210": 'rgba(250,50,231,1)',
            "211": '#9cbc3f',
            "212": '#505aa5',
            "213": '#d67d2c',
            "214": '#66bdaa',
            "215": '#576b43',
            "216": '#627a9d',
            "217": '#c19581',
            "218": '#735144',
            "219": '#ba5694',
            "220": '#1885a1',
            "1871164491": 'purple',
            "1871165693": 'red',
            "1871165694": "#9cbc3f",
            "1871165695": "#505aa5",
            "1871165696": "#d67d2c",
            "1871165697": "#66bdaa",
            "1871165698": 'black',
            "1871165699": "yellow",
            "1893058630": "#576b43",
            "1893058631": "red",
            "1893058632": "#627a9d",
            "1893058633": "red",
            "1893058634": "#c19581",
            "1893058635": "rgba(250,50,231,1)",
            "1893058636": "#ba5694",
            "1893058637": "#ba5694",
            "1893058638": "red",
            "1893058639": '#ffba37',
            "1893058640": '#008080',
            "1893058641": "red",
            "1893058642": "purple",
            "1893058643": "#1885a1",
            "1893058644": "#9cbc3f",
            "1893058645": "#505aa5",
            "1893058646": "#d67d2c",
            "1893058647": "#1885a1",
            "1893058648": "#ba5694",
            "1893058649": "#735144",
            "1893072156": "#627a9d",
            "1893072157": "#008080",
            "1893072158": "red",
            "1893072159": "#d67d2c",
            "1893072160": "#9cbc3f",
            "1893072161": "#008080",
            "1893072162": 'purple',
            "1893072163": '#9cbc3f',
        };
        return colors[idx]
    };
    async make(i,time){
        if(this.state.isPlay&&i>=this.state.playIdx){
            let {lineData,playSpeed}= this.state;
            const device_name=this.idToName(lineData.device_id);
            lineData=lineData.data;
            var allTime=(lineData[lineData.length-1].time-lineData[0].time)||1;
            var current=lineData[i+1].time-lineData[0].time;
            var timer=0;
            var a = new wgs84tobd09();
            let that=this;
            const xy = a.convert_xy(lineData[i+1].lat_lng[1],lineData[i+1].lat_lng[0]);
            const timeShow = moment(lineData[i+1].time).format('MM-DD HH:mm:ss');
            return  await new Promise(resolve => {
                that.setState({
                    playPosition:{
                        lng:xy[0],
                        lat:xy[1],
                        device_name,
                        time:timeShow
                    },
                    playIdx:i+1,
                    infoWindowPosition:null,
                    progress:parseInt(current/allTime*100),
                    center: {lng:xy[0], lat:xy[1]},
                });

                if(that.state.stayLists[0].length>0){
                     timer=moment(that.state.stayLists[0][that.state.activeTableIdx].start_time).valueOf();
                }
                if(lineData[i].time>timer&&that.state.activeTableIdx<that.state.stayLists[0].length-1){
                    that.setState({
                        activeTableIdx:that.state.activeTableIdx+1
                    })
                }
                // console.log(lineData[i].time,timer,moment(lineData[i].time).format('YYYY-MM-DD HH:mm:ss'),that.state.stayLists[0][that.state.activeTableIdx+1].start_time)
                if(this.state.playIdx===(lineData.length-1)){
                    that.setState({
                        // playIdx:0,
                        activeTableIdx:0,
                        isPlay:false
                    })
                }
                setTimeout(resolve, parseInt(time/parseInt(playSpeed)));
            });
        }
    }
    playRail=()=>{
        let {lineData}= this.state;
        let that=this;
        lineData=lineData.data;
        var arrTime=[];
        lineData.reduce(function (prev,next) {
            arrTime.push(next.time-prev.time);
            return next;
        });
        if(this.state.playIdx===(lineData.length-1)){
            that.setState({
                playIdx:0,
                // activeTableIdx:0,
                // isPlay:false
            })
        }
        var a = new wgs84tobd09();
        var p;
        this.setState({
            isPlay:!this.state.isPlay,
            infoWindowPosition:null
        },function () {
            p = that.make(0,arrTime[0]);
            for (let i = 1, len = arrTime.length; i < len; i++) {
                p = p.then(() => that.make(i,arrTime[i]));
            }
        });
        // const speed = item.speed / 1e3;
        // (async function() {
        //     for (let i = 0, len = arrTime.length; i < len; i++) {
        //         const m = arrTime[i];
        //         const xy = a.convert_xy(lineData[i+1].lat_lng[1],lineData[i+1].lat_lng[0]);
        //         await new Promise(resolve => {
        //             console.log(m,xy);
        //             that.setState({
        //                 playPosition:{
        //                     lng:xy[0],
        //                     lat:xy[1],
        //                 }
        //             });
        //             setTimeout(resolve, parseInt(m/6000));
        //         });
        //     }
        // })();
    }
    nextPoint=()=>{
        if(this.state.playIdx<this.state.lineData.data.length-1){
            let {lineData}= this.state;
            const device_name=this.idToName(lineData.device_id);
            lineData=lineData.data;
            var allTime=(lineData[lineData.length-1].time-lineData[0].time)||1;
            var current=lineData[this.state.playIdx+1].time-lineData[0].time;
            var a = new wgs84tobd09();
            const xy = a.convert_xy(lineData[this.state.playIdx+1].lat_lng[1],lineData[this.state.playIdx+1].lat_lng[0]);
            const timeShow = moment(lineData[this.state.playIdx+1].time).format('MM-DD HH:mm:ss');
            this.setState({
                playIdx:this.state.playIdx+1,
                playPosition:{
                    lng:xy[0],
                    lat:xy[1],
                    device_name,
                    time:timeShow
                },
                infoWindowPosition:null,
                progress:parseInt(current/allTime*100),
                center: {lng:xy[0], lat:xy[1]},
            });
            /**
             * 高亮表格行
             */
            var timer=0;
            if(this.state.stayLists[0].length>0){
                timer=moment(this.state.stayLists[0][this.state.activeTableIdx].start_time).valueOf();
            }
            if(lineData[this.state.playIdx+1].time>timer&&this.state.activeTableIdx<this.state.stayLists[0].length-1){
                this.setState({
                    activeTableIdx:this.state.activeTableIdx+1
                })
            }
            // console.log(lineData[i].time,timer,moment(lineData[i].time).format('YYYY-MM-DD HH:mm:ss'),that.state.stayLists[0][that.state.activeTableIdx+1].start_time)
            if(this.state.playIdx===(lineData.length-1)){
                this.setState({
                    // playIdx:0,
                    activeTableIdx:0,
                    isPlay:false
                })
            }

        }
    };
    prevPoint=()=>{
        if(this.state.playIdx>0){
            let {lineData}= this.state;
            const device_name=this.idToName(lineData.device_id);
            lineData=lineData.data;
            var allTime=(lineData[lineData.length-1].time-lineData[0].time)||1;
            var current=lineData[this.state.playIdx-1].time-lineData[0].time;
            var a = new wgs84tobd09();
            const xy = a.convert_xy(lineData[this.state.playIdx-1].lat_lng[1],lineData[this.state.playIdx-1].lat_lng[0]);
            const timeShow = moment(lineData[this.state.playIdx-1].time).format('MM-DD HH:mm:ss');
            this.setState({
                playIdx:this.state.playIdx-1,
                playPosition:{
                    lng:xy[0],
                    lat:xy[1],
                    device_name,
                    time:timeShow
                },
                infoWindowPosition:null,
                progress:parseInt(current/allTime*100),
                center: {lng:xy[0], lat:xy[1]},
            });

            /**
             * 高亮表格行
             */
            var timer=0;//停留点事间戳
            if(this.state.stayLists[0].length>0){
                timer=moment(this.state.stayLists[0][this.state.activeTableIdx].start_time).valueOf();
            }
            if(lineData[this.state.playIdx].time<timer&&this.state.activeTableIdx<=this.state.stayLists[0].length-1){
                this.setState({
                    activeTableIdx:this.state.activeTableIdx-1
                })
            }
            if(this.state.playIdx===(lineData.length-1)){
                this.setState({
                    // playIdx:0,
                    activeTableIdx:0,
                    isPlay:false
                })
            }
        }
    };
    handleSpeedChange=e=>{
        this.setState({
            playSpeed:e.target.value
        })
    }
    render() {
        const {
            infoWindowPosition,
            infoWindowText, isTrail,
            cur_device, deviceListVisible, checkedKeys,
            prevStatus, nextStatus,
            lineData, lines,
            today, demoId, currentPoint, searchDemoId,
            center, stayLists, stayListVisible,isFullScreen,mileage,
            activeTableIdx,playSpeed,playIdx,isPlay,playPosition,playRail,progress
        } = this.state;
        /**
         * 测试点聚合
         */
        const obj = [
            {
                device_id: 1111111,
                "startTime": 1535197093,
                "endTime": 1535107031,
                "lat": 30.193619,
                "lng": 120.201532,
                "name": "德信软件园",
                "address": "秋溢路601"
            },
            {
                device_id: 2222222222,
                "startTime": 1535205914,
                "endTime": 1535199996,
                "lat": 30.100045,
                "lng": 120.285524,
                "name": "杭州萧山南部物流城",
                "address": "浙江省杭州市萧山区联东路1881号"
            },
            {
                device_id: 3333333333,
                "startTime": 1535214403,
                "endTime": 1535214104,
                "lat": 31.197503,
                "lng": 120.533743,
                "name": "苏州市吴中区华源机械配件厂",
                "address": "后巷路3号"
            },
            {
                device_id: 444444444444,
                "startTime": 1535231383,
                "endTime": 1535215999,
                "lat": 31.441186,
                "lng": 120.481857,
                "name": "普洛斯望亭物流园北区",
                "address": "海盛路68号"
            },
            {
                device_id: 5555555555555,
                "startTime": 1535243203,
                "endTime": 1535242975,
                "lat": 33.143321,
                "lng": 119.430067,
                "name": "太平桥",
                "address": "扬州市宝应县"
            },
            {
                device_id: 66666666,
                "startTime": 1535244253,
                "endTime": 1535243302,
                "lat": 33.20891,
                "lng": 119.403145,
                "name": "八大家",
                "address": "扬州市宝应县老沿广线"
            },
            {
                device_id: 77777777777,
                "startTime": 1535245663,
                "endTime": 1535244511,
                "lat": 33.431251,
                "lng": 119.271786,
                "name": "淮安六洞服务区",
                "address": "江苏省淮安市淮安区"
            },
            {
                device_id: 888890,
                "startTime": 1535246293,
                "endTime": 1535245693,
                "lat": 33.631558,
                "lng": 119.158519,
                "name": "水木明瑟",
                "address": "江苏省淮安市清江浦区大同路古黄河湿地公园水木明瑟"
            },
            {
                device_id: 95345345,
                "startTime": 1535260543,
                "endTime": 1535259988,
                "lat": 34.870381,
                "lng": 118.216385,
                "name": "苍山立交",
                "address": "山东省临沂市苍山县"
            },
            {
                device_id: 10324534,
                "startTime": 1535266380,
                "endTime": 1535261488,
                "lat": 35.183569,
                "lng": 118.255659,
                "name": "祊河大桥",
                "address": "山东省临沂市兰山区"
            },
            {
                device_id: 11345,
                "startTime": 1535276713,
                "endTime": 1535266407,
                "lat": 35.203023,
                "lng": 118.259441,
                "name": "曹家屯村",
                "address": "临沂市兰山区"
            },
            {
                device_id: 124564565,
                "startTime": 1535279743,
                "endTime": 1535277969,
                "lat": 35.277904,
                "lng": 118.263124,
                "name": "汪沟立交",
                "address": "山东省临沂市费县"
            }
        ];
        const {marks, points} = this.stayHandler(obj, [1, 2]);

        const basicMapProps = {
            infoWindowPosition,
            infoWindowText,
            isTrail,
            onDeviceListVisible: this.handleDeviceListVisible,
            setEventHandler: this.setEventHandler,
            infoWindowHandler: this.infoWindowHandler,
            infoWindow: this.infoWindow,
            infoWindowTest: this.infoWindowTest,
            getCurrentPoint: this.getCurrentPointHandler,
            getCurrentLine: this.getCurrentLine,
            getRandomLineColor: this.getRandomLineColor,
            getStayPoints: this.getStayPoints,
            currentPoint,
            cur_device,
            checkedKeys,
            prevStatus,
            nextStatus,
            prevDay: this.prevDay,
            nextDay: this.nextDay,
            getDate: this.getDate,
            lineData,
            lines,
            today,
            center,
            stayLists,//停留点数据
            idToName:this.idToName,
            handleRequestFullScreen:this.handleRequestFullScreen,
            isFullScreen,
            marks,
            points,
            playSpeed,playIdx,isPlay,playPosition,
            playRail:this.playRail,
            prevPoint:this.prevPoint,
            nextPoint:this.nextPoint,
            progress,
            handleSpeedChange:this.handleSpeedChange
        };
        const that = this;

        return (
            <div>
                <BasicMap {...basicMapProps}>
                </BasicMap>
                <DeviceList onCheck={this.onCheck}
                               onVisible={this.handleDeviceListVisible}
                               onSelect={this.onSelect}
                               visible={deviceListVisible}
                               deviceIdList={searchDemoId}
                               isTrail={isTrail}
                               checkedKeys={checkedKeys}
                               mileage={mileage}
                               getRandomLineColor={this.getRandomLineColor}
                               clearCheckKeys={this.clearCheckKeys}
                               onChange={this.onChange}
                />
                {
                    isTrail && <StayList
                        points={stayLists}
                        activeTableIdx={activeTableIdx}
                        infoWindow={that.infoWindow}
                        visible={stayListVisible}
                        onClose={that.handleStayListVisible}
                    />
                }
            </div>
        );
    }
}
export default Index;